package cn.lookup.controller;

import cn.lookup.domain.Role;
import cn.lookup.domain.User;
import cn.lookup.service.RoleService;
import cn.lookup.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import java.util.List;

@Controller
@RequestMapping("/user")
public class UserController {
    @Autowired
    @Qualifier("userService")
    private UserService userService;
    @Autowired
    @Qualifier("roleService")
    private RoleService roleService;
    //获取用户列表
    @RequestMapping("/userList")
    public ModelAndView getUserList(ModelAndView modelAndView){
        List<User> userList = userService.getUserList();
        for (User user : userList) {
            Long userId = user.getId();
            List<Role> roles = roleService.getRolesByUserId(userId);
            user.setRoles(roles);
        }
        modelAndView.setViewName("user-list");
        modelAndView.addObject("userList",userList);
        return modelAndView;
    }
    //添加用户页面初始化角色列表
    @RequestMapping("/addUser")
    public ModelAndView addUser(ModelAndView modelAndView){
        List<Role> roleList = roleService.getRoleList();
        modelAndView.setViewName("user-add");
        modelAndView.addObject("roleList",roleList);
        return modelAndView;
    }
    //添加用户
    @RequestMapping("/submitAdd")
    public String submitAdd(User user,Long[] roleIds){
        userService.submitAdd(user,roleIds);
        return "redirect:/user/userList";
    }
    //删除用户
    @RequestMapping("/delete/{userId}")
    public String submitDelete(@PathVariable(value="userId") Long userId){
        userService.delete(userId);
        return "redirect:/user/userList";
    }
}
